package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;

/**
 * <p>到处某门课程的所有题目<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class ExportLmsQuestion {


    public static final String JS = "var video = document.getElementsByTagName(\"video\");if(video.length>0){ video[0].src = \"https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4\";}";


    public static void main(String[] args) throws Exception {
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


        String userName = "2237001202100";
        String pwd = "Ouchn@2021";
//        String subjectName = "企业现场管理基础";
//        Long courseId = 16502l;
        String subjectName =
                "当代中国政治制度";
        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码
        Thread.sleep(10000);

        //webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginId"))).sendKeys(username);

        WebElement loginBtn = driver.findElement(By.id("button"));

        loginBtn.click();

        Thread.sleep(10000);


        // 进入课程首页
        // div className = ouchnPc_index_course w
        // div className = ouchnPc_index_course_div

        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains(subjectName)) {
                we.findElement(By.tagName("a")).click();
                break;
            }
        }
        Util.switchToLast(driver);

        for (WebElement we : driver.findElements(By.cssSelector("div[class='activity-tab gtm-label ng-scope active']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains("形考任务")) {
                we.findElement(By.tagName("a")).click();
                break;
            }
        }


        // TODO 现在开始获取具体课程所有的答题链接：：


        List<String> urlTasks = Lists.newArrayList();

        urlTasks.add("https://lms.ouchn.cn/course/20000007226/learning-activity/full-screen#/exam/20000063543");
        urlTasks.add("https://lms.ouchn.cn/course/20000007226/learning-activity/full-screen#/exam/20000063544");
        urlTasks.add("https://lms.ouchn.cn/course/20000007226/learning-activity/full-screen#/exam/20000063545");
        urlTasks.add("https://lms.ouchn.cn/course/20000007226/learning-activity/full-screen#/exam/20000063546");


        boolean exportAnswer = false;


        List<Question> questions = Lists.newLinkedList();

        for (String urlTask : urlTasks) {
            driver.get(urlTask);
            Thread.sleep(10000);
            // ng-scope activity-content-bd


            //  for = confirm 点击勾选 我已知晓考试要求并承诺遵守考试纪律 ng-valid ng-touched ng-dirty ng-valid-parse ng-empty
            if (!exportAnswer) {
                try {
                    //  点击开始答题
                    driver.findElement(By.cssSelector("div[class='exam-button-container ng-scope']")).findElement(By.tagName("span")).click();

                    Thread.sleep(10*1000);

                    new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<WebElement>)
                            d -> Objects.requireNonNull(d).findElement(By.cssSelector("input[name='confirm']"))).click();

                    Thread.sleep(10*1000);
                    for (WebElement startAnswerWe : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                            d -> Objects.requireNonNull(d).findElements(By.cssSelector("button[class='button button-green medium ng-binding']")))) {
                        // button button-green medium ng-binding
                        if ("开始答题".equals(startAnswerWe.getText()) || "继续答题".equals(startAnswerWe.getText())) {
                            startAnswerWe.click();
                            break;
                        }

                    }


                } catch (Exception e) {

                }

            } else {
                driver.findElement(By.cssSelector("a[class='view-submission ng-scope']")).click();

            }


            // 找到所有的问题element
            Thread.sleep(10000);
            // FIXME 目前没发现有问题分页的！
            List<WebElement> webElements = findWeElements(driver, "li[ng-class='subject.type']", 20);


            for (WebElement e : webElements) {

                /**
                 * <li  class="subject ng-scope fill_in_blank">
                 *
                 * ng-if="subject.type == 'fill_in_blank'" 填空题
                 * subject ng-scope single_selection 单选题
                 * subject ng-scope multiple_selection 多选题
                 * subject ng-scope short_answer 简答题
                 * FIXME 获取class类来判断题型
                 */

                Question question = new Question();
                questions.add(question);

                // 题目类型
                String questionType = e.getAttribute("class");
                System.err.println("questionType:" + questionType);
                try {
                    if (questionType.equals("subject ng-scope text")) {
                        continue;
                    }
                    setQuestionType(question, questionType);
                } catch (Exception exception) {
                    exception.printStackTrace();
                    continue;
                }


                WebElement summaryTitleWe = e.findElement(By.cssSelector("div[class='summary-title']"));
                System.err.println("summaryTitleWe:" + summaryTitleWe.getText());

                // 获取题目的标题 FIXME 这里获取英语的阅读理解或者完型填空是有问题的！！！！！！！！
                // WebElement titleWe = summaryTitleWe.findElement(By.cssSelector("p[class='p0 ng-scope']"));
                //  WebElement titleWe = summaryTitleWe.findElement(By.cssSelector("p[class$='ng-scope']"));
                //   String title = summaryTitleWe.getText();
                StringBuilder titleSb = new StringBuilder();
                for (WebElement ngWe : summaryTitleWe.findElements(By.cssSelector("*[class$='ng-scope']"))) {
                    // 过滤掉题目的序号
                    if (!Strings.isNullOrEmpty(ngWe.getAttribute("ng-if"))) {
                        continue;
                    }
                    titleSb.append(ngWe.getText());
                }

                // 图像拖拉拽
                if(question.getQuestionType() == 8){


                    for(WebElement descWe:e.findElements(By.cssSelector("div[class='content-center desc']"))){
                        titleSb.append(descWe.getText());
                    }

                }
                String title = titleSb.toString();
                title = Util.dealContent(title);

                question.setTitle(title);

                try {
                    String answer = e.findElement(By.cssSelector("div[class='answer-options ng-scope answer-only']")).getText();
                    question.setCorrectArray(new String[]{answer});
                } catch (Exception e111) {

                }

                List<Item> items = Lists.newArrayList();
                question.setItems(items);
                if (question.getQuestionType() == 1 || question.getQuestionType() == 2) {
                    for (WebElement liWe : e.findElements(By.cssSelector("li[class='option ng-scope vertical']"))) {
                        String prefix = liWe.findElement(By.cssSelector("span[class='left']")).getText();
                        String content = liWe.findElement(By.cssSelector("span[class='pre-wrap simditor-viewer mathjax-process']")).getText();
                        Item item = new Item();
                        item.setPrefix(prefix);
                        item.setContent(content);
                        items.add(item);
                    }
                }

            }


        }

        // 输出JSON文件；  {id}-题型.json
        Collections.sort(questions);
        List<Map<String, Object>> answers = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> answerMap = new HashMap<>();
            answerMap.put("questionType", question.getQuestionType());
            answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
            answerMap.put("questionTitle", question.getTitle());
            answerMap.put("questionCode", MD5Utils.encode(subjectName + question.getTitle()));
            answerMap.put("items", question.getItems());
            answerMap.put("answers", question.getCorrectArray());
            if (question.getCorrectArray() != null && question.getCorrectArray().length > 0) {
                answerMap.put("answers", question.getCorrectArray());
            } else {
                answerMap.put("answers", Lists.newArrayList("标准答案"));
            }
            // 如果这里是完形填空  就默认为sendKeys
            if (question.getQuestionType() == 6) {
                answerMap.put("answerType", "send");
            } else {
                answerMap.put("answerType", "click");
            }

            answers.add(answerMap);
        }
        String rootPath = "d://lmsTmp//";
        FileUtils.write(new File(rootPath + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

        Thread.sleep(5000);

        Thread.sleep(500000000);

//
    }

    public static void setQuestionType(Question question, String type) throws Exception {
        switch (type) {
            case "subject ng-scope fill_in_blank":
                question.setQuestionType(4);
                question.setQuestionTypeDesc("填空题");
                break;
            case "subject ng-scope single_selection":
                question.setQuestionType(1);
                question.setQuestionTypeDesc("单选题");
                break;
            case "subject ng-scope multiple_selection":
                question.setQuestionType(2);
                question.setQuestionTypeDesc("多选题");
                break;
            case "subject ng-scope true_or_false":
                question.setQuestionType(3);
                question.setQuestionTypeDesc("判断题");
                break;
            case "subject ng-scope short_answer":
                question.setQuestionType(5);
                question.setQuestionTypeDesc("简答题");
                break;
            //subject ng-scope cloze
            case "subject ng-scope cloze":
                question.setQuestionType(6);
                question.setQuestionTypeDesc("完形填空");
                break;
            case "subject ng-scope matching":
            question.setQuestionType(8);
            question.setQuestionTypeDesc("匹配题-拖拉拽");
            break;
            default:
                throw new Exception("当前题型不支持自动答题！");
        }
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
